﻿#include "SqliteDB.h"
#include "global.h"
SqliteDB::SqliteDB(const QString& name) : m_db(QSqlDatabase::addDatabase("QSQLITE"))
{
    m_db.setDatabaseName(name);
    m_db.setPassword("111111");
    openDB();
}

SqliteDB::~SqliteDB()
{
    closeDB();
}

bool SqliteDB::InitDB(const QString &name)
{
    m_db.setDatabaseName(name);
    m_db.setPassword("111111");
    return openDB();
}

bool SqliteDB::openDB()
{
    if (m_db.isOpen())
        return true;

    if(!m_db.open())
    {
        mylog<< "Error: QSqlDatabase connection error:" << m_db.lastError();
        return false;
    }
    return true;
}

void SqliteDB::closeDB()
{
    if(m_db.isOpen())
    {
        m_db.close();
    }
}

QSqlDatabase SqliteDB::getDB()
{
    return m_db;
}

bool SqliteDB::tableExists(QString tableName)
{
    bool exists = false;
    QSqlQuery query(m_db);

    // 检查是否存在
    query.exec(QString("SELECT name FROM sqlite_master  WHERE type='table' AND name='%1';").arg(tableName));
    if(query.first())
    {
        exists = true;
    }

    return exists;
}

QStringList SqliteDB::tables()
{
    QStringList tableNames;

    QSqlQuery query(m_db);
    query.exec(QString("SELECT * FROM sqlite_master WHERE type='table'"));

    while(query.next())
    {
        QString tableName = query.value(1).toString();
        if (!tableName.startsWith("sqlite_"))
            tableNames.append(tableName);
    }

    return tableNames;
}

bool SqliteDB::executeQuery(QString query)
{
    QSqlQuery sql_query(m_db);
    bool result = sql_query.exec(query);
    if(!result)
    {
      mylog<<sql_query.lastError();
    }
    return result;
}

QVariant SqliteDB::lastInsertID()
{
    QSqlQuery query(m_db);
    query.prepare("SELECT last_insert_rowid()");
    if (query.exec() && query.first())
    {
        return query.value(0);
    }
    else
    {
        return QVariant();
    }
}

